package com.onion.express.plugins.qlexpress;

import com.onion.express.plugins.qlexpress.function.RegexpMatcher;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class QLExpressFactory {

    private static volatile ExpressRunner qlExpressRunner;

    public static ExpressRunner newRunner(){
        if(qlExpressRunner == null){
            synchronized (QLExpressFactory.class){
                if(qlExpressRunner == null){
                    qlExpressRunner = new ExpressRunner();
                    //添加绑定自定义Java方法
                    appendFunctions(qlExpressRunner);
                }
            }
        }
        return qlExpressRunner;
    }

    /**
     * 绑定自定义Java方法
     * @param expressRunner
     */
    private static void appendFunctions(ExpressRunner expressRunner){
        try {
            expressRunner.addFunctionOfClassMethod("now", System.class,
                    "currentTimeMillis", new Class[0], null);

            expressRunner.addFunctionOfClassMethod("isMatch", RegexpMatcher.class,
                    "isMatch", new Class[]{String.class, String.class}, null);

        } catch (Exception exp) {
            throw new RuntimeException("QLExpress绑定自定义Java方法出错：{}", exp);
        }
    }

    public static Object executeRule(String expressString, Map<String,Object> dataParam){
        ExpressRunner qlExpressRunner = QLExpressFactory.newRunner();
        IExpressContext<String, Object> qlExpressContext = new DefaultContext<>();
        for(String key : dataParam.keySet()){
            qlExpressContext.put(key, dataParam.get(key));
        }
        List<String> errorList = new ArrayList<>();
        try{
            return qlExpressRunner.execute(expressString, qlExpressContext, errorList, true, true, 3000);
        }catch (Exception exp){
            throw new RuntimeException("执行QlExpress出错!", exp);
        }
    }

    public static void main(String[] args) throws Exception{
        ExpressRunner qlExpressRunner = QLExpressFactory.newRunner();

        Log log = LogFactory.getFactory().getInstance(QLExpressFactory.class);

        String expressString = "if (css_inbound_all_count_last>0 && css_inbound_ai_count_last*1.0/css_inbound_all_count_last < 0.5) then {return true;} else {return false;}";
        IExpressContext<String, Object> context = new DefaultContext<>();
        context.put("css_inbound_all_count_last", 10);
        context.put("css_inbound_ai_count_last", 4);

        List<String> errorList = new ArrayList<>();
        Object qlResult = qlExpressRunner.execute(expressString, context, errorList, true, true, log);

        System.out.println(qlResult);
    }

}